package com.jinhuhang.u2.myselfmodule.engine.bank;

import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.activity.ZSimpleBaseActivity;
import com.jinhuhang.u2.entity.BankCity;
import com.jinhuhang.u2.entity.BankInfoBean;
import com.jinhuhang.u2.entity.BankListBean;
import com.jinhuhang.u2.entity.UserSingleResult;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.ui.BottomDialogManager;
import com.jinhuhang.u2.ui.DefaultDialog;
import com.jinhuhang.u2.ui.itemview.BankItemView;
import com.jinhuhang.u2.util.RSAEncryptor;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

import static com.jinhuhang.u2.R.id.bank_subname;

/**
 * Created by OnionMac on 17/9/14.
 */

public class BankActivity extends ZSimpleBaseActivity implements BankContract.View {

    @Bind(R.id.toolbar_back)
    ImageView mToolbarBack;
    @Bind(R.id.toolbar_name)
    TextView mToolbarName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.bank_name)
    BankItemView mBankName;
    @Bind(R.id.bank_card)
    BankItemView mBankCard;
    @Bind(R.id.bank_bankcard)
    BankItemView mBankBankcard;
    @Bind(R.id.bank_bank)
    BankItemView mBankBank;
    @Bind(R.id.bank_location)
    BankItemView mBankLocation;
    @Bind(bank_subname)
    BankItemView mBankSubname;
    @Bind(R.id.btn_bank)
    AppCompatButton mBtnBank;
    @Bind(R.id.bank_all)
    LinearLayout mBankAll;
    private BankContract.Presenter mPresenter;
    private boolean mFirst;
    private List<BankListBean> mBankList = new ArrayList<>();
    private ArrayList<String> mBankNameList = new ArrayList<>();
    private ArrayList<String> mBankCity = new ArrayList<>();
    private Map<String,String> mBankCityMap = new HashMap<>();
    private Map<String,String> mBankCardMap = new HashMap<>();
    private BottomDialogManager mBottomDialogManagerBankList;
    private BottomDialogManager mBottomDialogManagerCity;
    Map<String,String> mHMap = new HashMap<>();
    @Override
    protected void initView() {
        mToolbarName.setText(R.string.bind_bankcard);
        mToolbarBack.setOnClickListener(v -> finish());

        mBottomDialogManagerBankList = new BottomDialogManager(this);
        mBottomDialogManagerBankList.setTitle("选择银行");

        mBottomDialogManagerCity = new BottomDialogManager(this);
        mBottomDialogManagerCity.setTitle("选择城市");

        mHMap = new HashMap<>();
    }

    @Override
    protected void initData() {
        /**
         * 初始加载城市列表
         */
        mPresenter.getBankInfo(getUserId());
        mPresenter.getBankList(getUserId());
        mPresenter.getCity(getUserId());
    }

    @Override
    protected void initListener() {
        mBottomDialogManagerBankList.setOkListener(t -> {
            mBankBank.selectOk(t);
        });

        mBankBank.setOnClickListener(v -> {
            mBottomDialogManagerBankList.show();
        });
        mBankLocation.setOnClickListener(v -> {
            mBottomDialogManagerCity.show();
        });
        mBottomDialogManagerCity.setOkListener(t -> {
            mBankLocation.selectOk(t.trim());
        });
        mBtnBank.setOnClickListener(v -> {
            String name = mBankName.getEditTextString();//名字
            String bankcard = mBankBankcard.getEditTextString();//银行卡号
            String idcard = mBankCard.getEditTextString();//身份证号
            String subName = mBankSubname.getEditTextString(); //开户支行
            String bankName = mBankBank.getSelectInfo(); //银行卡银行
            String location = mBankLocation.getSelectInfo();//银行卡归属地
            String zhihang = mBankSubname.getEditTextString();//支行
            mHMap.put("userId",getUserId());
            mHMap.put("username",name);
            mHMap.put("bank_id",mBankCardMap.get(bankName));
            mHMap.put("idcard",idcard);
            mHMap.put("cardno",bankcard);
            mHMap.put("card_city",mBankCityMap.get(location));
            mHMap.put("bank_city",mBankCityMap.get(location));
            mHMap.put("card_zhihang",zhihang);
            if(TextUtils.isEmpty(name) || TextUtils.isEmpty(bankcard) || TextUtils.isEmpty(idcard)
                    || TextUtils.isEmpty(subName) || TextUtils.isEmpty(bankName) || TextUtils.isEmpty(location)){
                showMessage("请填写完整信息!");
                return;
            }

            if(idcard.length() != 18){
                showMessage("请输入18位身份证号");
                return;
            }

            if(bankcard.length() < 11 && bankcard.length() > 20){
                showMessage("请输入正确位数的银行卡号");
                return;
            }
            if(mFirst){
                mPresenter.checkIdCard(getUserId(),idcard);
            }else{
                /**
                 * 直接提交
                 */
                mPresenter.checkIdCardOnFaild(getUserId(),idcard);
            }
        });
    }

    /**
     * 绑定银行卡
     */
    private void bindBankCard() {
        DefaultDialog defaultDialog = new DefaultDialog(this);
        defaultDialog.show();
        defaultDialog.startCountDown();
        defaultDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {
                mPresenter.bindBankCard(mHMap);
            }

            @Override
            public void onRight() {

            }
        });
        defaultDialog.setOnCountDownEndListener(() -> {
            mPresenter.bindBankCard(mHMap);
        });
    }

    @Override
    public void onResultGetBankInfo(HttpWrapperList<BankInfoBean> o) {
        String status = getUser().getStatus();
        mBankAll.setVisibility(View.VISIBLE);
        if("1".equals(status)){
            mBankBank.setEnabled(false);
            mBankLocation.setEnabled(false);
            mBtnBank.setVisibility(View.GONE);
        }

        BankInfoBean singleData = o.getSingleData();
        Logger.i("张琦"+status+new Gson().toJson(singleData));

        if(singleData == null){
            /**
             * 数据为空 说明是第一次进入
             */
            mFirst = true;
            return;
        }
        /**
         * 绑定银行卡成功  不能修改
         */
//        StringBuffer sb = new StringBuffer();
//        String name = singleData.getName();
//        if(name != null){
//            for (int i = 0;i < name.length() - 1; i++){
//                sb.append("*");
//            }
//            sb.append(name.substring(name.length() - 1));
//        }
        mBankName.status( singleData.getName(),status);
        mBankCard.status(RSAEncryptor.androidDecryt(singleData.getCard()),status); //TODO 解码
        mBankBankcard.status(RSAEncryptor.androidDecryt(singleData.getCardNo()),status);
        mBankBank.status(singleData.getBankName(),status);
        mBankLocation.status(singleData.getCityName().trim(),status);
        mBankSubname.status(singleData.getCardZhihang(),status);
    }

    @Override
    public void onResultCheckIdCard(HttpWrapperList<String> o) {
        if(Constant.SUCCESS_CODE == o.code) {
            bindBankCard();
        }else{
            showMessage(o.getInfo());
        }
    }

    @Override
    public void onResultBankCityList(HttpWrapperList<BankCity> o) {
        ArrayList<BankCity> data = o.getData();
        for (int i = 0; i < data.size(); i++) {
            mBankCity.add(data.get(i).getCity_name());
            mBankCityMap.put(data.get(i).getCity_name().trim(),data.get(i).getCity_code());
        }
        mBottomDialogManagerCity.setData(mBankCity);
    }

    @Override
    public void onResultGetBankList(HttpWrapperList<BankListBean> o) {
        mBankList = o.getData();
        for (BankListBean bankBean : mBankList) {
            mBankNameList.add(bankBean.getBankName());
            mBankCardMap.put(bankBean.getBankName(),bankBean.getBankCode());
        }

        mBottomDialogManagerBankList.setData(mBankNameList);
    }

    @Override
    public void onBindBankCardResult(HttpWrapperList<UserSingleResult> o) {
        if(Constant.SUCCESS_CODE == o.code){
            finish();
        }else{
            showMessage(o.getInfo());
        }
    }

    @Override
    protected void attachPre() {
        mPresenter = new BankPresenter(this, mCompositeSubscription);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bank;
    }


}
